import React, { useState, useEffect } from 'react';
import { Button, notification } from 'antd';

const CaptchaComponent = () => {
    const [captchaText, setCaptchaText] = useState('');
    const [expiryTime, setExpiryTime] = useState(null);
    const [countdown, setCountdown] = useState(0);
    const [buttonText, setButtonText] = useState('生成验证码');
    const [api, contextHolder] = notification.useNotification();

    const generateCaptcha = () => {
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let captcha = '';
        for (let i = 0; i < 6; i++) {
            captcha += characters.charAt(Math.floor(Math.random() * characters.length));
        }
        setCaptchaText(captcha);
        setExpiryTime(Date.now() + 60 * 1000); // 1 minute in milliseconds
        startCountdown();
        api.open({
            message: '短信验证码',
            description:captcha,
            style: {
              display:'flex',
              justifyContent:'center',
            }, 
          });
    };

    const startCountdown = () => {
      setCountdown(60);
      // setButtonText(`重新生成 (60s)`);
  
      let interval; // 在这里声明定时器变量，以便在组件卸载时可以访问到它
  
      const updateCountdown = () => {
          setCountdown((prevCountdown) => {
              const newCountdown = prevCountdown - 1;
              // console.log(`倒计时更新，剩余秒数：${newCountdown}`);
              if( newCountdown == 0 ){
                clearInterval(interval);
                setButtonText('生成验证码');
              }else{
                setButtonText(`重新生成 (${newCountdown})`);
              }
              return newCountdown;
          });
      };
  
      // const updateButtonText = () => {
          // const currentCountdown = countdown;
          // 确保秒数显示格式为两位数，不足两位前面补0
          // const formattedSeconds = String(currentCountdown).padStart(2, '0');
          // setButtonText(`重新生成 (${formattedSeconds}s)`);
          // console.log(`按钮文本更新为：重新生成 (${formattedSeconds}s)`);
      // };
  
      interval = setInterval(() => {
          updateCountdown();
          if (countdown === 1) {
              handleCountdownEnd();
          }
      }, 1000);
  
      // 使用 useEffect 钩子来确保在组件卸载时清除定时器
      // useEffect(() => {
      //     return () => {
      //         if (interval) {
      //             clearInterval(interval);
      //             console.log('组件卸载，清除定时器');
      //         }
      //     };
      // }, []);
  };

    useEffect(() => {
        if (expiryTime) {
            const timer = setTimeout(() => {
                setCaptchaText('');
                setExpiryTime(null);
            }, expiryTime - Date.now());
            return () => clearTimeout(timer);
        }
        console.log(countdown);
        
    }, [expiryTime]);


  // import {BorderTopOutlined} from '@ant-design/icons';
  // const [api, contextHolder] = notification.useNotification();
  // const openNotification = (placement) => {
  //   api.info({
  //     message: `Notification ${placement}`,
  //     description:
  //       'This is the content of the notification. This is the content of the notification. This is the content of the notification.',
  //     placement,
  //   });
    return (
        <div>
            {contextHolder}
            {/* <p>{captchaText}</p> */}
            <Button
                // icon={<BorderTopOutlined />}
                style={{
                    width: 100,
                    height: 35,
                    background: 'rgb(255,244,215)',
                    border: 0,
                    color: 'rgb(247,181,0)',
                    borderRadius: '3px',
                    marginLeft:'10px'
                }}
                onClick={generateCaptcha}
            >
                {buttonText}
            </Button>
        </div>
    );
};

export default CaptchaComponent;